import { reactive, onUnmounted, onMounted } from '@vue/runtime-core'
import { getScreenSize, throttle, isMobile } from '../../utils'

export const useBullet = (planeInfo) => {
  const { width, height } = getScreenSize()
  const delay = 100
  const bulletWidth = 30
  const bulletHeight = 60
  const bullets = reactive([])
  function addBullet() {
    bullets.push({
      x: planeInfo.x + 45,
      y: planeInfo.y - 30,
      width: bulletWidth,
      height: bulletHeight
    })
  }
  // 移动端和PC端发射子弹
  function handleAddBullet(e) {
    if(e.code === 'Space' && !isMobile) {
      addBullet()
    }
    if(isMobile && e.touches) {
      addBullet()
    }
  }
  onMounted(() => { 
    if(isMobile) {
      document.addEventListener('touchstart', handleAddBullet)
      document.addEventListener('touchmove', throttle(handleAddBullet, delay))
    }else {
      document.addEventListener('keydown', handleAddBullet)
    }
  })
  onUnmounted(() => { 
    if(isMobile) {
      document.removeEventListener('touchstart', handleAddBullet)
      document.removeEventListener('touchmove', throttle(handleAddBullet, delay))
    }else {
      document.removeEventListener('keydown', handleAddBullet)
    }
  })
  return {
    bullets
  }
}
